﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace PlanTasks.Commons
{
    public class PlanTaskList
    {
        private readonly XmlDocument _ConfigXml = new XmlDocument();
        private static PlanTaskList _PlanTaskList = null;
        private PlanTaskManagerConfig _PlanTaskManagerConfig;
        private XmlNode _SrcElement;
        private string _XPath;
        public List<PlanTask> PlanTasks { get; set; }

        private PlanTaskList()
        {
            _PlanTaskManagerConfig = PlanTaskManagerConfig.GetObject();
            Init();
        }

        public static PlanTaskList GetObject()
        {
            if (_PlanTaskList == null)
                _PlanTaskList = new PlanTaskList();
            return _PlanTaskList;
        }

        public void Init()
        {
            //获取"PlanTaskList.xml"文件路径
            _XPath = _PlanTaskManagerConfig.SyncPath;
            if (_XPath.Equals("."))
                _XPath = AppDomain.CurrentDomain.BaseDirectory;
            //判断路径下是否有"PlanTaskList.xml"文件，如果没有则提示没有后关闭。
            if (!File.Exists(Path.Combine(_XPath, "PlanTaskList.xml")))
            {
                MessageBox.Show(@"没有找到任务文件，请将任务文件放在正确位置再打开软件。", @"提示", MessageBoxButtons.OK);
                Environment.Exit(0);
            }
            //如果有则读取任务列表
            _ConfigXml.Load(Path.Combine(_XPath, "PlanTaskList.xml"));
            _SrcElement = _ConfigXml.DocumentElement?.SelectSingleNode("/PlanTaskList");
            FillPlanTasks();
        }

        /// <summary>
        ///     从CodingPlan.xml文件得到任务列表，并填充到List中去
        /// </summary>
        /// <returns></returns>
        private void FillPlanTasks()
        {
            if (_SrcElement != null)
            {
                if (PlanTasks == null)
                    PlanTasks = new List<PlanTask>(_SrcElement.ChildNodes.Count);
                else
                    PlanTasks.Clear();
                foreach (XmlElement ele in _SrcElement.ChildNodes)
                {
                    var pt = new PlanTask
                    {
                        Id = ele.GetAttribute("Id"),
                        Content = ele.GetAttribute("Content"),
                        Type = ele.GetAttribute("type"),
                        State = ele.GetAttribute("state"),
                        InsData = ele.GetAttribute("insDate"),
                        FulFillData = ele.GetAttribute("fulFillDate")
                    };
                    if (ele.ChildNodes.Count > 0)
                    {
                        foreach (XmlElement cele in ele.ChildNodes)
                        {
                            var tc = new TaskComment
                            {
                                Id = cele.GetAttribute("Id"),
                                Time = cele.GetAttribute("Time"),
                                Content = cele.GetAttribute("Content")
                            };
                            pt.Comments.Add(tc);
                        }
                    }
                    PlanTasks.Insert(0, pt);
                }
            }
        }

        /// <summary>
        ///     根据任务id获取任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PlanTask GetTaskFromId(string id)
        {
            var task = new PlanTask();
            foreach (var pt in PlanTasks)
                if (pt.Id.Equals(id))
                    return pt;
            return task;
        }

        public void SaveNewComment(string id, TaskComment tc)
        {
            var xn = _SrcElement.SelectSingleNode("//PlanTaskList//task[@Id = " + id + "]");
            var nc = _ConfigXml.CreateElement("comment");
            nc.SetAttribute("Id", tc.Id);
            nc.SetAttribute("Time", tc.Time);
            nc.SetAttribute("Content", tc.Content);
            xn?.AppendChild(nc);
            _ConfigXml.Save(Path.Combine(_XPath, "PlanTaskList.xml"));
        }

        public void SaveNewPlanTask(PlanTask pt)
        {
            var xn = _SrcElement.SelectSingleNode("//PlanTaskList");
            var nc = _ConfigXml.CreateElement("task");
            nc.SetAttribute("Id", pt.Id);
            nc.SetAttribute("Content", pt.Content);
            nc.SetAttribute("type", pt.Type);
            nc.SetAttribute("state", pt.State);
            nc.SetAttribute("insDate", pt.InsData);
            nc.SetAttribute("fulFillDate", pt.FulFillData);
            xn?.AppendChild(nc);
            _ConfigXml.Save(Path.Combine(_XPath, "PlanTaskList.xml"));
        }

        public void SaveEditPlanTask(PlanTask pt)
        {
            var nc = (XmlElement) _ConfigXml.SelectSingleNode("//PlanTaskList//task[@Id = " + pt.Id + "]");
            if (nc != null)
            {
                nc.SetAttribute("type", pt.Type);
                nc.SetAttribute("state", pt.State);
                nc.SetAttribute("Content", pt.Content);
                nc.SetAttribute("insDate", pt.InsData);
                nc.SetAttribute("fulFillDate", pt.FulFillData);
            }
            _ConfigXml.Save(Path.Combine(_XPath, "PlanTaskList.xml"));
        }

        public void DeleteAllPlanTask()
        {
            if (this.PlanTasks.Count <= 0) return;

            for (int i = 0; i < PlanTasks.Count; i++)
            {
                XmlNode xn =
                    _ConfigXml.DocumentElement.SelectSingleNode("//PlanTaskList//task[@Id = " + PlanTasks[i].Id + "]");
                _ConfigXml.DocumentElement.RemoveChild(xn);
                //PlanTasks.Remove(PlanTasks[i]);
            }
            PlanTasks.Clear();
            _ConfigXml.Save(Path.Combine(_XPath, "PlanTaskList.xml"));
        }
    }
}